<template>
    <div>
        <a-form ref="formRef" @finish="handleFinish" :model="form" name="basic" :label-col="{ span: 8 }">
            <a-row :gutter="16">

                <a-col :span="12">
                    <a-form-item label="项目名称" name="proName" :rules="[{ required: true }]">
                        <a-input-search :disabled="disabled" v-model:value="form.proName" style="width: 100%"
                            placeholder="选择的项目" @click="onSearch" @search="onSearch" />

                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="项目编号" name="proId">

                        <a-input v-model:value="form.proId" disabled style="width: 100%" placeholder="选择的项目" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="甲方名称" name="proCustom">
                        <a-input v-model:value="form.proCustom" disabled style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="发票类型" name="type" :rules="[{ required: true }]">
                        <!-- <a-input v-model:value="form.invoiceType" disabled style="width: 100%" placeholder="" /> -->

                        <a-select :getPopupContainer="trigger => trigger.parentNode" ref="select" :disabled="disabled" v-model:value="form.type" :options="invoiceType"
                            style="width: 100%">
                            <!-- <a-select-option value="普通增值税发票">普通增值税发票</a-select-option>
                            <a-select-option value="增值税专用发票">增值税专用发票</a-select-option>
                            <a-select-option value="手撕发票">手撕发票</a-select-option> -->
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="税率" name="taxPoint" :rules="[{ required: true }]">
                        <a-input-number :precision="2" :min="0" :max="1" v-model:value="form.taxPoint"
                            :disabled="disabled" style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="开票金额" name="amount" :rules="[{ required: true }]">
                        <a-input-number :precision="2" :min="0" v-model:value="form.amount" :disabled="disabled"
                            style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="开票日期" name="invoiceTime" :rules="[{ required: true }]">

                        <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" :disabledDate="disabledDate" valueFormat="YYYY-MM-DD hh:mm:ss" :disabled="disabled"
                            v-model:value="form.invoiceTime" style="width: 100%" placeholder="" />

                    </a-form-item>
                </a-col>
                <a-col :span="12">

                    <a-form-item label="发票号码" name="code"
                        :rules="[{ required: true, message: '请输入发票号码' }, { min: 8, message: '发票号码至少需要8个字符' }]">
                        <a-input-number v-model:value="form.code" :maxlength="14" :disabled="disabled" style="width: 100%"
                            placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="预计回款时间" name="receiveTime" :rules="[{ required: true }]">

                        <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" :disabledDate="disabledDate"  valueFormat="YYYY-MM-DD hh:mm:ss" :disabled="disabled"
                            v-model:value="form.receiveTime" style="width: 100%" placeholder="" />

                    </a-form-item>
                </a-col>

            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="纳税人识别号" name="taxId" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                        <a-input v-model:value="form.taxId" :disabled="disabled" style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>

            </a-row>
            <a-row :gutter="16">

                <a-col :span="24">
                    <a-form-item label="地址、电话" name="contact" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                        <a-input v-model:value="form.contact" :disabled="disabled" style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="开户行及账号" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" name="bankAccount">
                        <a-input v-model:value="form.bankAccount" :disabled="disabled" style="width: 100%"
                            placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>




            <a-row :gutter="16" v-if="disabled">
                <a-col :span="12">
                    <a-form-item label="申请人" name="createUserName">
                        <a-input v-model:value="form.createUserName" disabled style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="申请部门" name="orgName">
                        <a-input v-model:value="form.orgName" disabled style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16" v-if="disabled">
                <a-col :span="12">
                    <a-form-item label="申请日期" name="createTime">
                        <a-input v-model:value="form.createTime" disabled style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16" class="mb-2">

                <a-col :span="6" class="text-left" style="font-weight: 600;">
                    开票内容
                    <!-- <span style="font-weight: 100;color: red;">（针对销售业务）</span> -->
                </a-col>
                <a-col :span="18" class="text-right">
                    <!-- <a-button class="ml-2" v-if="!isShow" @click="add" type="primary">新增一条</a-button> -->
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-table :dataSource="form.purMaterialList" bordered :columns="columns" :pagination="false"
                        class="mb-2">
                        <template #bodyCell="{ column, record, index }">
                            <template v-if="column.key === 'index'">
                                {{ index + 1 }}
                            </template>


                        </template>
                    </a-table>
                </a-col>
            </a-row>
            <system :value="form"></system>
        </a-form>
        <projectSelection ref="proSelect" @onClose="prSelectOk" :value="form.proSelectRecords" />

    </div>
</template>

<script setup>
import system from '@/components/Task/system.vue'
import { invoiceType } from '@/utils/constants.js'
import api from '@/api/finance/invoic/index'
import costApi from '@/api/pm/cost/index'
import projectSelection from '@/components/pm/projectSelection.vue'
import dayjs from 'dayjs';
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
    },

    {
        title: '产品名称',
        dataIndex: 'material',
        key: 'material'
    },
    {
        title: '型号规格',
        dataIndex: 'unit',
        key: 'unit'
    },
    {
        title: '数量',
        dataIndex: 'quantities',
        key: 'quantities'
    },
    {
        title: '单价',
        dataIndex: 'unitPrice',
        key: 'unitPrice'
    },
    {
        title: '下单编号',
        dataIndex: 'orderNumber',
        key: 'orderNumber'
    }
]
const disabledDate = current => {
    return current && current < dayjs().endOf('day');
};


const form = ref({})
const formRef = ref()

const proSelect = ref()
const onSearch = () => {
    proSelect.value.show()
}
const prSelectOk = (selectedRowKeys, selectRecords) => {
    console.log("项目选择ok ", selectedRowKeys, selectRecords)
    form.value.proId = selectRecords[0].id
    form.value.proName = selectRecords[0].name
    form.value.proCustom = selectRecords[0].custom
    form.value.proSelectRecords = selectRecords;

    costApi.detail({ proId: form.value.proId }).then((res) => {
        console.log(" costApi.detail res:", res)
        mSelectOk(res.records)
    })
}

const mSelectOk = (rows) => {
    const selectedRows = JSON.parse(JSON.stringify(rows));
    selectedRows.map(x => {
        x.totalCost = x.quantities * x.costUnitPrice
        x.comTotalPrice = x.quantities * x.comUnitPrice
        x.totalLaborCost = x.quantities * x.laborUnitPrice
        x.totalUnitPrice = x.quantities * x.unitPrice
        x.comTotalPrice = x.quantities * x.synUnitPrice
    })
    form.value.purMaterialList = selectedRows
}

const submit = () => {
    formRef.value.validate().then(() => {
        handleFinish(form.value)
    }).catch((err) => {

    });
}
const handleFinish = (values) => {

    console.log("handleFinish", values);
    if (!form.value.id) {
        api.add(values).then(() => {
            onClose(true);
        })
    } else {
        values.id = form.value.id;
        api.edit(values).then(() => {
            onClose(true);
        })
    }
};
const isEdit = ref(false)
const show = (record) => {
    if (record) {
        form.value = { ...record }
        costApi.detail({ proId: form.value.proId }).then((res) => {
            console.log(" costApi.detail res:", res)
            mSelectOk(res.records)
        })
        isEdit.value = true;
    } else {
        form.value = {}
        isEdit.value = false
    }
}



const props = defineProps({
    value: {
        type: Object,
        default: () => { }
    },
    disabled: {
        type: Boolean,
        default: () => false
    }
})

watch(
    () => props.value,
    (newVal, oldVal) => {
        if (newVal) {
            form.value = { ...newVal }
            if (form.value.proId) {
                costApi.detail({ proId: form.value.proId }).then((res) => {
                    mSelectOk(res.records)
                })
            }
        }
    },
    { deep: true, immediate: true }
)

const getData = () => {
    return new Promise((resolve, reject) => {
        formRef.value.validate().then(() => {
            form.value.flowCode = "FLW_INVOICE"
            resolve(form.value)
        }).catch((err) => {
            reject(err)
        });
    })
}
// 重置
const resetForm = () => {
    formRef.value.resetFields()
}
defineExpose({
    getData,
    resetForm,
    show,
    submit,
    isEdit
})

const emits = defineEmits(['OnClose'])
const onClose = (refresh) => {
    emits('OnClose', refresh)
};
</script>
